package com.lwc.backendsinglestructure.strategy.loginStrategy;

import cn.hutool.core.util.StrUtil;
import com.lwc.backendsinglestructure.domain.dto.user.LoginForm;
import com.lwc.backendsinglestructure.domain.entity.User;
import com.lwc.backendsinglestructure.exception.BusinessException;
import com.lwc.backendsinglestructure.exception.ErrorCode;
import com.lwc.backendsinglestructure.mapper.UserMapper;
import com.lwc.backendsinglestructure.strategy.LoginHandler;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 正常用户名密码登录
 */
@Component("normal_Login")
public class NormalLoginHandler implements LoginHandler {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(LoginForm loginRequest) {
        // 1.参数校验
        String username = loginRequest.getUsername();
        String password = loginRequest.getPassword();
        if (StrUtil.hasBlank(username, password)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        // todo 2.校验验证码

        // 3.比对数据库
        // 先对用户密码进行加密再比对
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOneByQuery(queryWrapper);
        if(user == null){
            throw new BusinessException(ErrorCode.USER_NOT_FOUND_ERROR);
        }
        if(!password.equals(user.getPassword())){
            throw new BusinessException(ErrorCode.PASSWORD_ERROR);
        }
        // 4.返回结果
        return user;
    }
}
